const express = require('express');
const OSS = require('ali-oss');
const cors = require('cors');
const path = require('path');

const app = express();
const port = process.env.PORT || 3000;

app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname)));

app.post('/api/delete', async (req, res) => {
    const { accessKeyId, accessKeySecret, region, bucket } = req.body;

    if (!accessKeyId || !accessKeySecret || !region || !bucket) {
        return res.status(400).json({ message: '缺少必要的参数' });
    }

    try {
        const client = new OSS({
            accessKeyId,
            accessKeySecret,
            region,
            bucket
        });

        let deletedCount = 0;
        let marker = '';

        do {
            const result = await client.list({
                marker,
                'max-keys': 1000
            });

            if (result.objects && result.objects.length > 0) {
                const objects = result.objects.map(obj => obj.name);
                await client.deleteMulti(objects);
                deletedCount += objects.length;
                console.log(`已删除文件:`, objects);
                console.log(`当前累计删除数量: ${deletedCount}`);
            }

            marker = result.nextMarker;
        } while (marker);

        res.json({ deletedCount });
    } catch (error) {
        console.error('删除文件时发生错误:', error);
        res.status(500).json({ message: error.message });
    }
});

app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
}); 